//package org.jeecg.modules.deepseek.config;
//
//import com.fasterxml.jackson.annotation.JsonInclude;
//import com.fasterxml.jackson.annotation.JsonProperty;
//import lombok.Data;
//import org.springframework.ai.model.ApiKey;
//import org.springframework.ai.model.ModelOptionsUtils;
//import org.springframework.ai.model.SimpleApiKey;
//import org.springframework.ai.retry.RetryUtils;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.MediaType;
//import org.springframework.http.ResponseEntity;
//import org.springframework.util.Assert;
//import org.springframework.util.LinkedMultiValueMap;
//import org.springframework.util.MultiValueMap;
//import org.springframework.web.client.ResponseErrorHandler;
//import org.springframework.web.client.RestClient;
//import org.springframework.web.reactive.function.client.WebClient;
//import reactor.core.publisher.Flux;
//import reactor.core.publisher.Mono;
//
//import java.util.List;
//import java.util.concurrent.atomic.AtomicBoolean;
//import java.util.function.Consumer;
//import java.util.function.Predicate;
//
//public class DeepSeekApi {
//
//    private static final Predicate<String> SSE_DONE_PREDICATE = "[DONE]"::equals;
//    private static final String DEFAULT_CHAT_MODEL = "deepseek-default";
//    private final String completionsPath;
//    private final RestClient restClient;
//    private final WebClient webClient;
//
//    // 构造函数
//    public DeepSeekApi(String baseUrl, String apiKey) {
//        this(baseUrl, new SimpleApiKey(apiKey), new LinkedMultiValueMap<>(),
//             "/v1/chat/completions", RestClient.builder(), WebClient.builder(),
//             RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER);
//    }
//
//    public DeepSeekApi(String baseUrl, ApiKey apiKey, MultiValueMap<String, String> headers,
//                      String completionsPath, RestClient.Builder restClientBuilder,
//                      WebClient.Builder webClientBuilder, ResponseErrorHandler responseErrorHandler) {
//        Assert.hasText(baseUrl, "Base URL must not be empty");
//        Assert.notNull(apiKey, "API Key must not be null");
//        Assert.hasText(completionsPath, "Completions Path must not be empty");
//        this.completionsPath = completionsPath;
//
//        Consumer<HttpHeaders> finalHeaders = (h) -> {
//            h.setBearerAuth(apiKey.getValue());
//            h.setContentType(MediaType.APPLICATION_JSON);
//            h.addAll(headers);
//        };
//
//        this.restClient = restClientBuilder
//                .baseUrl(baseUrl)
//                .defaultHeaders(finalHeaders)
//                .defaultStatusHandler(responseErrorHandler)
//                .build();
//
//        this.webClient = webClientBuilder
//                .baseUrl(baseUrl)
//                .defaultHeaders(finalHeaders)
//                .build();
//    }
//
//    // 同步聊天完成
//    public ResponseEntity<ChatCompletion> chatCompletionEntity(ChatCompletionRequest chatRequest,
//                                                              MultiValueMap<String, String> additionalHttpHeader) {
//        Assert.notNull(chatRequest, "请求体不能为空");
//        Assert.isTrue(!chatRequest.stream, "请求必须将 stream 属性设置为 false");
//        Assert.notNull(additionalHttpHeader, "额外的 HTTP 头不能为空");
//
//        return restClient.post()
//                .uri(completionsPath)
//                .headers(headers -> headers.addAll(additionalHttpHeader))
//                .body(chatRequest)
//                .retrieve()
//                .toEntity(ChatCompletion.class);
//    }
//
//    // 流式聊天完成
//    public Flux<ChatCompletionChunk> chatCompletionStream(ChatCompletionRequest chatRequest,
//                                                         MultiValueMap<String, String> additionalHttpHeader) {
//        Assert.notNull(chatRequest, "请求体不能为空");
//        Assert.isTrue(chatRequest.stream, "请求必须将 stream 属性设置为 true");
//
//        AtomicBoolean isInsideTool = new AtomicBoolean(false);
//
//        return webClient.post()
//                .uri(completionsPath)
//                .headers(headers -> headers.addAll(additionalHttpHeader))
//                .body(Mono.just(chatRequest), ChatCompletionRequest.class)
//                .retrieve()
//                .bodyToFlux(String.class)
//                .takeUntil(SSE_DONE_PREDICATE)
//                .filter(SSE_DONE_PREDICATE.negate())
//                .map(content -> ModelOptionsUtils.jsonToObject(content, ChatCompletionChunk.class));
//    }
//
//    // 请求类
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public static class ChatCompletionRequest {
//        @JsonProperty("messages")
//        private List<ChatCompletionMessage> messages;
//        @JsonProperty("stream")
//        private boolean stream;
//        @JsonProperty("model")
//        private String model;
//        @JsonProperty("temperature")
//        private Double temperature;
//
//        public ChatCompletionRequest(List<ChatCompletionMessage> messages, boolean stream) {
//            this(messages, stream, DEFAULT_CHAT_MODEL, 0.7);
//        }
//
//        public ChatCompletionRequest(List<ChatCompletionMessage> messages, boolean stream,
//                                   String model, Double temperature) {
//            this.messages = messages;
//            this.stream = stream;
//            this.model = model;
//            this.temperature = temperature;
//        }
//
//        public List<ChatCompletionMessage> getMessages() { return messages; }
//        public boolean isStream() { return stream; }
//        public String getModel() { return model; }
//        public Double getTemperature() { return temperature; }
//
//        public void setMessages(List<ChatCompletionMessage> messages) { this.messages = messages; }
//        public void setStream(boolean stream) { this.stream = stream; }
//        public void setModel(String model) { this.model = model; }
//        public void setTemperature(Double temperature) { this.temperature = temperature; }
//    }
//
//    // 消息类
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public static class ChatCompletionMessage {
//        @JsonProperty("content")
//        private Object content;
//        @JsonProperty("role")
//        private Role role;
//
//        public enum Role {
//            @JsonProperty("system") SYSTEM,
//            @JsonProperty("user") USER,
//            @JsonProperty("assistant") ASSISTANT,
//            @JsonProperty("tool") TOOL
//        }
//
//        public ChatCompletionMessage(Object content, Role role) {
//            this.content = content;
//            this.role = role;
//        }
//
//        public Object getContent() { return content; }
//        public String getRole() {
//            return role.toString();
//        }
//    }
//
//    // 完成响应类
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public static class ChatCompletion {
//        @JsonProperty("id")
//        private String id;
//        @JsonProperty("choices")
//        private List<Choice> choices;
//        @JsonProperty("created")
//        private Long created;
//        @JsonProperty("model")
//        private String model;
//        @JsonProperty("usage")
//        private Usage usage;
//
//        public ChatCompletion(String id, List<Choice> choices, Long created,
//                            String model, String serviceTier, String systemFingerprint,
//                            String object, Usage usage) {
//            this.id = id;
//            this.choices = choices;
//            this.created = created;
//            this.model = model;
//            this.usage = usage;
//        }
//
//        public String getId() { return id; }
//        public List<Choice> getChoices() { return choices; }
//        public Long getCreated() { return created; }
//        public String getModel() { return model; }
//        public Usage getUsage() { return usage; }
//
//        public static class Choice {
//            @JsonProperty("finish_reason")
//            private String finishReason;
//            @JsonProperty("index")
//            private Integer index;
//            @JsonProperty("message")
//            private ChatCompletionMessage message;
//            @JsonProperty("logprobs")
//            private Object logprobs;
//
//            public Choice(String finishReason, Integer index, ChatCompletionMessage message, Object logprobs) {
//                this.finishReason = finishReason;
//                this.index = index;
//                this.message = message;
//                this.logprobs = logprobs;
//            }
//
//            public String getFinishReason() { return finishReason; }
//            public Integer getIndex() { return index; }
//            public ChatCompletionMessage getMessage() { return message; }
//            public Object getLogprobs() { return logprobs; }
//        }
//    }
//
//    // 流式响应类
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    @Data
//    public static class ChatCompletionChunk {
//        @JsonProperty("id")
//        private String id;
//        @JsonProperty("choices")
//        private List<ChunkChoice> choices;
//        @JsonProperty("created")
//        private Long created;
//        @JsonProperty("model")
//        private String model;
//        @JsonProperty("usage")
//        private Usage usage;
//
//        public ChatCompletionChunk(String id, List<ChunkChoice> choices, Long created,
//                                 String model, String serviceTier, String systemFingerprint,
//                                 String object, Usage usage) {
//            this.id = id;
//            this.choices = choices;
//            this.created = created;
//            this.model = model;
//            this.usage = usage;
//        }
//
//        public String getId() { return id; }
//        public List<ChunkChoice> getChoices() { return choices; }
//        public Long getCreated() { return created; }
//        public String getModel() { return model; }
//        public Usage getUsage() { return usage; }
//
//        public static class ChunkChoice {
//            @JsonProperty("finish_reason")
//            private String finishReason;
//            @JsonProperty("index")
//            private Integer index;
//            @JsonProperty("delta")
//            private ChatCompletionMessage delta;
//            @JsonProperty("logprobs")
//            private Object logprobs;
//
//            public ChunkChoice(String finishReason, Integer index, ChatCompletionMessage delta, Object logprobs) {
//                this.finishReason = finishReason;
//                this.index = index;
//                this.delta = delta;
//                this.logprobs = logprobs;
//            }
//
//            public String getFinishReason() { return finishReason; }
//            public Integer getIndex() { return index; }
//            public ChatCompletionMessage getDelta() { return delta; }
//            public Object getLogprobs() { return logprobs; }
//        }
//    }
//
//    // 使用统计类
//    @JsonInclude(JsonInclude.Include.NON_NULL)
//    public static class Usage {
//        @JsonProperty("prompt_tokens")
//        private Integer promptTokens;
//        @JsonProperty("completion_tokens")
//        private Integer completionTokens;
//        @JsonProperty("total_tokens")
//        private Integer totalTokens;
//
//        public Usage(Integer promptTokens, Integer completionTokens, Integer totalTokens) {
//            this.promptTokens = promptTokens;
//            this.completionTokens = completionTokens;
//            this.totalTokens = totalTokens;
//        }
//
//        public Integer getPromptTokens() { return promptTokens; }
//        public Integer getCompletionTokens() { return completionTokens; }
//        public Integer getTotalTokens() { return totalTokens; }
//    }
//
//    // 构建器类
//    public static class Builder {
//        private String baseUrl = "https://api.deepseek.com";
//        private ApiKey apiKey;
//        private MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
//        private String completionsPath = "/v1/chat/completions";
//        private RestClient.Builder restClientBuilder = RestClient.builder();
//        private WebClient.Builder webClientBuilder = WebClient.builder();
//        private ResponseErrorHandler responseErrorHandler = RetryUtils.DEFAULT_RESPONSE_ERROR_HANDLER;
//
//        public Builder baseUrl(String baseUrl) {
//            this.baseUrl = baseUrl;
//            return this;
//        }
//
//        public Builder apiKey(String apiKey) {
//            this.apiKey = new SimpleApiKey(apiKey);
//            return this;
//        }
//
//        public Builder headers(MultiValueMap<String, String> headers) {
//            this.headers = headers;
//            return this;
//        }
//
//        public Builder completionsPath(String completionsPath) {
//            this.completionsPath = completionsPath;
//            return this;
//        }
//
//        public DeepSeekApi build() {
//            Assert.notNull(apiKey, "API Key must be set");
//            return new DeepSeekApi(baseUrl, apiKey, headers, completionsPath,
//                                 restClientBuilder, webClientBuilder, responseErrorHandler);
//        }
//    }
//}